from django.db import models
from django.utils.translation import gettext_lazy as _
from ckeditor_uploader.fields import RichTextUploadingField
from PIL import Image
import os
from django.conf import settings
import logging
import shutil

class SiteInfo(models.Model):
    """
    网站信息模型，用于管理网站的基本信息，如网站名称、描述、关于页面等
    """
    site_name = models.CharField(_('网站名称'), max_length=100, default='CursorRulesCN')
    site_description = models.TextField(_('网站描述'), blank=True)
    about_content = RichTextUploadingField(_('关于页面内容'), blank=True)
    contact_email = models.EmailField(_('联系邮箱'), blank=True)
    logo = models.ImageField(_('网站Logo'), upload_to='logo/', blank=True, null=True)
    updated_at = models.DateTimeField(_('更新时间'), auto_now=True)
    
    class Meta:
        verbose_name = _('网站信息')
        verbose_name_plural = _('网站信息')
    
    def __str__(self):
        return self.site_name
    
    @classmethod
    def get_site_info(cls):
        """获取网站信息，如果不存在则创建默认信息"""
        site_info, created = cls.objects.get_or_create(
            pk=1,
            defaults={
                'site_name': 'CursorRulesCN',
                'site_description': '各种语言和场景的cursor规则展示网站',
                'about_content': '欢迎来到CursorRulesCN，这里收集了各种语言和场景下的cursor规则。'
            }
        )
        return site_info

class SiteVisit(models.Model):
    """网站访问记录模型"""
    page = models.CharField(_('访问页面'), max_length=255)
    ip_address = models.GenericIPAddressField(_('IP地址'), blank=True, null=True)
    user_agent = models.TextField(_('用户代理'), blank=True, null=True)
    referrer = models.URLField(_('来源网址'), blank=True, null=True)
    visited_at = models.DateTimeField(_('访问时间'), auto_now_add=True)
    
    class Meta:
        verbose_name = _('网站访问')
        verbose_name_plural = _('网站访问')
        indexes = [
            models.Index(fields=['page']),
            models.Index(fields=['visited_at']),
        ]
        
    def __str__(self):
        return f"{self.page} - {self.visited_at}"

class PageVisitCount(models.Model):
    """页面访问计数模型"""
    CONTENT_TYPE_CHOICES = (
        ('site', _('网站总访问')),
        ('rule', _('规则')),
        ('article', _('文章')),
    )
    
    content_type = models.CharField(_('内容类型'), max_length=20, choices=CONTENT_TYPE_CHOICES)
    object_id = models.PositiveIntegerField(_('对象ID'), default=0)
    page_path = models.CharField(_('页面路径'), max_length=255, blank=True, null=True)
    visit_count = models.PositiveIntegerField(_('访问次数'), default=0)
    created_at = models.DateTimeField(_('创建时间'), auto_now_add=True)
    updated_at = models.DateTimeField(_('更新时间'), auto_now=True)
    
    class Meta:
        verbose_name = _('页面访问计数')
        verbose_name_plural = _('页面访问计数')
        unique_together = ('content_type', 'object_id')
        indexes = [
            models.Index(fields=['content_type', 'object_id']),
            models.Index(fields=['page_path']),
        ]
        
    def __str__(self):
        return f"{self.content_type} - {self.object_id} ({self.visit_count}次访问)"
        
    @classmethod
    def increment_count(cls, content_type, object_id=0, page_path=None):
        """增加访问计数"""
        obj, created = cls.objects.get_or_create(
            content_type=content_type,
            object_id=object_id,
            defaults={'page_path': page_path}
        )
        obj.visit_count += 1
        obj.save()
        return obj.visit_count

class ActionCount(models.Model):
    """用户操作计数模型（如复制规则等）"""
    ACTION_TYPE_CHOICES = (
        ('copy_rule', _('复制规则')),
        ('submit_rule', _('提交规则')),
        ('view_rule_md', _('查看规则MD格式')),
        ('download_rule_md', _('下载规则为MD文件')),
        ('copy_rule_url', _('复制规则URL')),
    )
    
    action_type = models.CharField(_('操作类型'), max_length=30, choices=ACTION_TYPE_CHOICES)
    object_id = models.PositiveIntegerField(_('对象ID'), default=0)
    count = models.PositiveIntegerField(_('操作次数'), default=0)
    created_at = models.DateTimeField(_('创建时间'), auto_now_add=True)
    updated_at = models.DateTimeField(_('更新时间'), auto_now=True)
    
    class Meta:
        verbose_name = _('用户操作计数')
        verbose_name_plural = _('用户操作计数')
        unique_together = ('action_type', 'object_id')
        
    def __str__(self):
        return f"{self.get_action_type_display()} - ID:{self.object_id} ({self.count}次)"
    
    @classmethod
    def increment_count(cls, action_type, object_id=0):
        """增加操作计数"""
        obj, created = cls.objects.get_or_create(
            action_type=action_type,
            object_id=object_id
        )
        obj.count += 1
        obj.save()
        return obj.count

class Advertisement(models.Model):
    """广告模型"""
    title = models.CharField(_('广告标题'), max_length=100)
    description = RichTextUploadingField(_('广告描述'), blank=True, null=True, config_name='basic_ckeditor')
    image = models.ImageField(
        _('广告图片'), 
        upload_to='banners/',
        help_text=_('建议尺寸：1200px × 600px (宽高比2:1)，将自动调整为固定比例')
    )
    url = models.URLField(_('链接地址'))
    is_active = models.BooleanField(_('是否激活'), default=True)
    click_count = models.PositiveIntegerField(_('点击次数'), default=0)
    display_order = models.PositiveSmallIntegerField(_('显示顺序'), default=0)
    created_at = models.DateTimeField(_('创建时间'), auto_now_add=True)
    
    class Meta:
        verbose_name = _('广告')
        verbose_name_plural = _('广告')
        ordering = ['display_order', '-created_at']
        
    def __str__(self):
        return self.title
    
    def increment_click(self):
        """增加点击次数"""
        self.click_count += 1
        self.save(update_fields=['click_count'])
        return self.click_count
        
    def save(self, *args, **kwargs):
        """保存广告时确保图片路径正确"""
        logger = logging.getLogger(__name__)
        
        # 记录操作开始
        is_new = self.pk is None
        logger.info(f"{'创建' if is_new else '更新'}广告: {self.title}")
        
        # 处理图片路径
        if self.image:
            # 修复路径中可能存在的嵌套ads目录问题
            image_name = self.image.name
            if 'ads/ads/' in image_name:
                self.image.name = image_name.replace('ads/ads/', 'ads/')
                logger.info(f"修复嵌套路径: {image_name} -> {self.image.name}")
            
            # 确保图片以ads/开头
            if not self.image.name.startswith('ads/'):
                self.image.name = f'ads/{self.image.name}'
                logger.info(f"修正图片路径: {self.image.name}")
        
        # 先保存模型确保图片文件被上传
        super().save(*args, **kwargs)
        
        # 检查并修复图片路径
        if self.image:
            try:
                media_root = settings.MEDIA_ROOT
                image_path = os.path.join(media_root, self.image.name)
                
                # 检查图片是否存在
                if not os.path.exists(image_path):
                    logger.warning(f"图片路径不存在: {image_path}")
                    
                    # 尝试查找可能的路径
                    possible_path = os.path.join(media_root, os.path.basename(self.image.name))
                    if os.path.exists(possible_path):
                        # 确保ads目录存在
                        ads_dir = os.path.join(media_root, 'ads')
                        if not os.path.exists(ads_dir):
                            os.makedirs(ads_dir)
                            logger.info(f"创建ads目录: {ads_dir}")
                        
                        # 复制文件到正确位置
                        shutil.copy(possible_path, image_path)
                        logger.info(f"图片已从 {possible_path} 复制到 {image_path}")
                    else:
                        logger.error(f"无法找到广告图片: {self.image.name}")
                
            except Exception as e:
                logger.error(f"处理广告图片时出错: {e}")
